package com.wafer.server.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.wafer.server.http.HttpRequest;
import com.wafer.server.http.HttpResponse;

/**
 * 流对象整理工具
 * @author wanbo
 *
 */

public class StreamUtil {
	
	private static Logger logger = Logger.getLogger(StreamUtil.class);
	
	/**
	 * 将Socket请求数据转换成HttpServlet请求对象
	 * 
	 * 步骤: 1.从Socket中获取输入流对象
	 *       2.将InputStream转换成InputStreamReader， 再将InputStreamReader转换成BufferedReader
	 *       3.从BufferedReader中逐行读取数据(根据HTTP协议，第一行为请求行，接下来是请求头并且每行一个，所以要逐行解析)
	 * 
	 * @param     socket  
	 * @return    http请求对象
	 * @throws IOException 
	 */
	public static HttpRequest streamToRequest(Socket socket) throws IOException {
		logger.debug("开始处理Socket数据转换为HTTP请求");
		InputStream is = socket.getInputStream();
		int availableData = is.available();
		byte[] b = new byte[availableData];
		is.read(b);
		String[] dataLines = new String(b).split("\r\n");
		
		logger.info(JSON.toJSONString(dataLines));
		
		for(int i = 0; i < dataLines.length; i++) {
		  System.out.println(String.format("行数 %d data:%s", i, dataLines[i]));
		}
		
		return null;
	}
	
	/**
	 * 
	 * @return
	 * @throws IOException 
	 */
	public static void putResponseToSocket(HttpResponse response, Socket socket) throws IOException {
		OutputStream outputStream = socket.getOutputStream();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(SocketThreadPoolUtil.HttpResponseString);
		stringBuilder.append("Hello World");
		System.out.println(stringBuilder.toString());
		outputStream.write(stringBuilder.toString().getBytes());
	}

}
